package maa.action.admin.course;

import maa.action.Action;
import maa.action.ActionResult;
import maa.dao.h2.CourseDAOimpl;
import maa.dao.DAOCommand;
import maa.dao.DAOManager;
import maa.database.ConnectionPool;
import maa.entity.Course;
import maa.action.ActionException;
import maa.dao.DAOException;
import maa.util.FieldValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class UpdateCourse implements Action {
    @Override
    public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        ActionResult actionResult = new ActionResult();
        final Course course = new Course();
        course.setUuid(UUID.fromString(req.getParameter("uuid").substring(0, req.getParameter("uuid").length() - 1)));
        String courseName = req.getParameter("courseName");
        String desc = req.getParameter("courseDescription");
        String price = req.getParameter("price");
        if (!FieldValidator.isValidCourseName(courseName)) {
            req.setAttribute("incorrect_name", "Invalid course name");
            actionResult.setResult("course-update");
            return actionResult;
        }
        if (!FieldValidator.isValidCourseDescription(desc)) {
            req.setAttribute("incorrect_description", "Invalid description");
            actionResult.setResult("course-update");
            return actionResult;
        }
        if (!FieldValidator.isValidPrice(price)) {
            req.setAttribute("incorrect_price", "Invalid price");
            actionResult.setResult("course-update");
            return actionResult;
        }
        course.setCourseName(courseName);
        course.setCourseDescription(desc);
        course.setCourseMonthlyPrice(Double.valueOf(price));
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = new DAOManager(connectionPool.getConnection());
        DAOCommand daoCommand = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                CourseDAOimpl courseDAO = daoManager.getCourseDAO();
                try {
                    return courseDAO.update(course);
                } catch (DAOException e) {
                    throw new ActionException("Exception in courseDAO.update(course)");
                }
            }
        };
        Boolean flag = (Boolean) daoManager.executeAndClose(daoCommand);
        if (flag) {
            session.removeAttribute("course");
            actionResult.setResult("admin-cabinet");
            actionResult.setRedirected(true);
        } else actionResult.setResult("admin-cabinet");
        return actionResult;
    }
}
